//
//  ViewController.m
//  ox
//
//  Created by 喻杰 on 2016/10/26.
//  Copyright © 2016年 fengge. All rights reserved.
//

#define waterfallCell @"waterfallCell"
#define waterfallheader @"waterfallHeader"
#define withCoordateRecords @"select count(r_id) as count,poi_name,max(lat) as lat,max(lon) as lon from ox_record where lat <>0 and lon <>0 group by poi_name order by count(r_id) desc limit ?,?"
#define myNavTitle @"选择位置"
#define myAnnotation @"myAnnotation"


#import "ViewController.h"



@interface ViewController ()

@end

@implementation ViewController

@synthesize map,locationService,search,center,lat,lon,poiName,address,arr,index,page,pageSize,helper;

- (void)viewDidLoad {
    [super viewDidLoad];
    map = [[BMKMapView alloc]initWithFrame:self.view.bounds];
    // [view setBuildingsEnabled:YES];
    //  [view setOverlookEnabled:YES];
    [map setShowMapPoi:YES];
    [map setMapScaleBarPosition:CGPointMake(10, self.view.bounds.size.height)];
    [map setShowMapScaleBar:YES];
    map.logoPosition =BMKLogoPositionRightBottom;
    [map setMapPadding:UIEdgeInsetsMake(0, 0, 0, 10)] ;
    
    page = 0;
    pageSize = 10;
    index = 0;
    
    // [view setMapType:BMKMapTypeSatellite];
    [map setShowsUserLocation:YES];
    [map setDelegate:self];
    [self.view addSubview:map];
    
    helper = [[DBHelper alloc]init];
    
    if([self.navigationItem.title isEqual: myNavTitle]){
        search = [[BMKGeoCodeSearch alloc] init];
        search.delegate = self;
        locationService = [[BMKLocationService alloc]init];
        locationService.delegate = self;
        //启动LocationService
        [locationService setDesiredAccuracy:kCLLocationAccuracyBest];
        [locationService setDistanceFilter:20];
        [locationService startUserLocationService];
        
        center = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cross"]];
        center.frame = CGRectMake((self.view.bounds.size.width-24)/2, (self.view.bounds.size.height-24)/2, 24, 24);
        [self.view addSubview:center];
        
    }else{
        UIBarButtonItem* right = [[UIBarButtonItem alloc]initWithTitle:@"下一个" style:UIBarButtonItemStylePlain target:self action:@selector(nextFoot:)];
        right.tag = 1;
        UIBarButtonItem* middle = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(nextFoot:)];
        middle.tag = 3;
        UIBarButtonItem* left = [[UIBarButtonItem alloc]initWithTitle:@"上一个" style:UIBarButtonItemStylePlain target:self action:@selector(nextFoot:)];
        left.tag = 2;
        self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:right,left, nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -- BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    if(search){
        BMKReverseGeoCodeOption * option = [[BMKReverseGeoCodeOption alloc]init];
        [option setReverseGeoPoint:CLLocationCoordinate2DMake(mapView.centerCoordinate.latitude, mapView.   centerCoordinate.longitude)];
        [search reverseGeoCode:option];
    }
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    DDLogInfo(@"%@",result.addressDetail.city);
    BMKPoiInfo *poi = [result.poiList firstObject];
    lat = result.location.latitude;
    lon = result.location.longitude;
    poiName = poi.name;
    address = result.address;
}

-(void) chooseAddress:(UIBarButtonItem *) sender{
    DDLogInfo(@"%@",address);
    self.chooseAddress(lat,lon,poiName,address);
    [self.navigationController popViewControllerAnimated:YES];
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:myAnnotation];
        newAnnotationView.image = [UIImage imageNamed:@"location"];
        //newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}

-(void)viewWillAppear:(BOOL)animated{
    [map viewWillAppear];
    map.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}

-(void)viewWillDisappear:(BOOL)animated{
    [map viewWillDisappear];
    map.delegate = nil; // 不用时，置nil
}

-(void)viewDidAppear:(BOOL)animated{
    if(![self.navigationItem.title isEqual: myNavTitle]){
        NSInteger end = index >pageSize-1 ? index+1 : (page+1)*pageSize;
        arr = [helper listBy:withCoordateRecords params:@[@(0),@(end)]];
        if(arr.count>0){
            for (int i=0; i<=index; i++) {
                NSMutableDictionary* dic = [arr objectAtIndex:i];
                BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
                DDLogInfo(@"%@",dic);
                NSString* latStr = [dic objectForKey:@"lat"];
                lat = [latStr floatValue];
                NSString* lonStr = [dic objectForKey:@"lon"];
                lon = [lonStr floatValue];
                poiName = [dic objectForKey:@"poi_name"];
                [dic objectForKey:@"lat"];
                NSString * countStr =[dic objectForKey:@"count"];
                annotation.coordinate = CLLocationCoordinate2DMake(lat, lon);
                annotation.title = poiName;
                annotation.subtitle = [NSString stringWithFormat:@"共(%@)条",countStr];
                [map addAnnotation:annotation];
            }
            BMKPointAnnotation* last = [[map annotations]lastObject];
            if(last)
                [map setCenterCoordinate:last.coordinate];
        }
    }else{
        
        //根据坐标定位
        BMKUserLocation* userLocation = [locationService userLocation];
        if(userLocation){
            [map setCenterCoordinate:userLocation.location.coordinate];
        }else{
            if(lat!=0&&lon!=0){
                [map setCenterCoordinate:CLLocationCoordinate2DMake(lat, lon)];
            }
        }
        
        //默认按照定位的中点查询一次
        BMKReverseGeoCodeOption * option = [[BMKReverseGeoCodeOption alloc]init];
        [option setReverseGeoPoint:[map centerCoordinate]];
        [search reverseGeoCode:option];
    }
}

- (void)viewDidDisappear:(BOOL)animated{
    [map removeAnnotations:[map annotations]];
}


//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    [map setCenterCoordinate:coord animated:YES];
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    DDLogInfo(@"%f",view.annotation.coordinate.latitude);
}

- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view{
    PhotoWallController* photoWall = [[PhotoWallController alloc]init];
    [photoWall setLat:view.annotation.coordinate.latitude];
    [photoWall setLon:view.annotation.coordinate.longitude];
    [photoWall setPoiName:view.annotation.title];
    photoWall.navigationItem.title = view.annotation.title;
    [self.navigationController pushViewController:photoWall animated:YES];
}


-(void)nextFoot:(UIBarButtonItem*) sender{
    if(sender.tag == 1){
        //没有数据刷新一次吧
        if(arr.count == 0 ){
            return;
        }
        index++;
        BOOL needAddAnnotation = YES;
        if(index > arr.count-1){
            page++;
            NSMutableArray<NSMutableDictionary*>* array = [helper listBy:withCoordateRecords params:@[@(page*pageSize),@((page+1)*pageSize)]];
            if(array.count>0){
                [arr addObjectsFromArray:array];
            }else{
                index = arr.count-1;
                page--;
                needAddAnnotation = NO;
            }
        }
        if(needAddAnnotation){
            NSMutableDictionary* dic = [arr objectAtIndex:index];
            BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
            NSString* latStr = [dic objectForKey:@"lat"];
            lat = [latStr floatValue];
            NSString* lonStr = [dic objectForKey:@"lon"];
            lon = [lonStr floatValue];
            poiName = [dic objectForKey:@"poi_name"];
            [dic objectForKey:@"lat"];
            NSString * countStr =[dic objectForKey:@"count"];
            annotation.coordinate = CLLocationCoordinate2DMake(lat, lon);
            annotation.title = poiName;
            annotation.subtitle = [NSString stringWithFormat:@"共(%@)条",countStr];
            [map addAnnotation:annotation];
        }
        BMKPointAnnotation* lastAnnotation = [[map annotations]lastObject];
        [map setCenterCoordinate:lastAnnotation.coordinate];
    }else{
        if([map annotations].count == 0){
            return;
        }
        index--;
        if(index < 0){
            index = 0;
        }else{
            [map removeAnnotation:[[map annotations] lastObject]];
        }
        BMKPointAnnotation* annotation = [[map annotations] objectAtIndex:index];
        [map setCenterCoordinate:annotation.coordinate];
    }
}

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
    DDLogInfo(@"%f",userLocation.heading.trueHeading);
}


@end
